package com.example.demo.cim.client.service.impl;

import com.example.demo.cim.client.config.AppConfiguration;
import com.example.demo.cim.client.service.MsgLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2019-01-23
 **/
@Service
public class AsyncMsgLogger implements MsgLogger {

    private final static Logger LOGGER = LoggerFactory.getLogger(AsyncMsgLogger.class);

    private final static int DEFAULT_QUEUE_SIZE = 16;

    private BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<String>(DEFAULT_QUEUE_SIZE);

    private volatile boolean started = false;

    private Worker worker;

    @Autowired
    private AppConfiguration appConfiguration;

    @Override
    public void log(String msg) {
        startMsgLogger();

        try {
            blockingQueue.put(msg);
        } catch (InterruptedException e) {
            LOGGER.error("InterruptedException", e);
        }
    }


    private class Worker extends Thread {
        @Override
        public void run() {
            while(started) {
                try{
                    String msg = blockingQueue.take();
                    writeLog(msg);
                } catch(InterruptedException e) {
                    break;
                }
            }
        }
    }


    /**
     * 开始工作
     */
    private void startMsgLogger() {
        if(started) {
            return;
        }
        worker.setDaemon(true);
        worker.setName("AsyncMsgLogger-Worker");
        started = true;
        worker.start();
    }

    private void writeLog(String msg) {
        LocalDate today = LocalDate.now();
        int year = today.getYear();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();

        String dir = appConfiguration.getMsgLoggerPath() + appConfiguration.getUserName() + "/";
        String fileName = dir + year + month + day + ".log";

        Path file = Paths.get(fileName);
        boolean exists = Files.exists(Paths.get(dir), LinkOption.NOFOLLOW_LINKS);
        try {
            if (!exists) {
                Files.createDirectories(Paths.get(dir));
            }
            List<String> lines = Arrays.asList(msg);
            Files.write(file, lines, Charset.forName("UTF-8"), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
        } catch (IOException e) {
            LOGGER.info("IOException", e);
        }
    }
}

